//
//  HuoYuanDetailViewController.m
//  Rabbit
//
//  Created 阿帕 on 2019/12/17.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "HuoYuanDetailViewController.h"
#import "CYWebViewViewController.h"

#import "OderDetailTFView.h"
#import "OrderInfoView.h"
#import "CarTeamViewController.h"


#define DefaultLocationTimeout 10
#define DefaultReGeocodeTimeout 5
#define QRIMG_WIDTH (ScreenW-120)/2

@interface HuoYuanDetailViewController ()<YunDanOrderDetailDelegate, AMapLocationManagerDelegate>
{
    NSString *_shuLiangString;
    NSString *_cheShuString;
    NSString *_danJiaString;
    NSString *_timeString;
    BOOL _isRequesting;
}
@property(strong, nonatomic)UIScrollView *scrollView;

@property(strong, nonatomic)OderDetailTFView    *oderDetailTFView;
@property(strong, nonatomic)OrderInfoView       *orderInfoView;
@property(nonatomic, strong)AMapLocationManager *locationManager;
@property(nonatomic, strong)NSDictionary        *dataDic;


@end

@implementation HuoYuanDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _isRequesting = NO;
    
    [self initBaseView];
    
    [self configLocationManager];
}

- (void)initBaseView {
    
    self.navigationItem.title = @"货源详情";
    
    self.scrollView.backgroundColor = BackgroundColor;
    
//    //0独立司机 1车队 2车队司机
//    DebugLog(@"司机身份%@", [UserDefaultUtil valueForKey:DRIVER_TYPE]);
//    isQuote 0非报价
//    coalNumber 0货源单
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@/%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER,_orderCode) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN],} withVC:self netName:@"货源详情信息" success:^(id response, NSString *msg) {
        
        _dataDic = response;
        
        [self.scrollView addSubview:self.oderDetailTFView];
        
        [self.scrollView addSubview:self.orderInfoView];
        
        self.oderDetailTFView.orderInfoDic = response;
        
        self.orderInfoView.response = response;
        
        self.scrollView.contentSize = CGSizeMake(ScreenW, self.orderInfoView.cy_bottom);

    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

#pragma mark - YunDanOrderDetailDelegate
- (void)calculateSelfViewHeight:(NSInteger)height {
    self.orderInfoView.top = 20 + height;
    self.scrollView.contentSize = CGSizeMake(ScreenW, self.orderInfoView.cy_bottom);
}
- (void)getTextFieldAndDateValue:(NSString *)shuliang andCheShu:(NSString *)cheshu andDanjia:(NSString *)danjia andDate:(NSString *)date {
    DebugLog(@"%@",shuliang);
    
    _shuLiangString = shuliang;
    _cheShuString = cheshu;
    _danJiaString = danjia;
    _timeString = date;
}

- (void)orderDetailButtonClick:(NSInteger)index andOrderState:(NSInteger)state LastWeight:(NSString *)lastWeight NotReceivedCount:(NSString *)notReceivedCount {
    
    [self.view endEditing:YES];
    
    if (_isRequesting == NO) {
        
        //接单1001 选择日期1000
        if (index == 1001) {
            /**
             0 非报价单 货源单 独立司机
             1 非报价单 非货源单 独立司机
             2 报价单 货源单 独立司机
             3 报价单 非货源单 独立司机
             4 非报价单 货源单 车队
             5 非报价单 非货源单 车队
             6 报价单 货源单 车队
             7 报价单 非货源单 车队
             */
            
            NSMutableDictionary *muDic = [NSMutableDictionary dictionary];
            NSString *urlString = @"";
            
            if (state == 0) {
                if ([DCSpeedy isBlankString:_shuLiangString] == YES) {
                    [XSInfoView showInfo:@"承运数量为空" onView:self.view];
                    return;
                }
                
                [muDic setValue:_shuLiangString forKey:@"perWeight"];
                [muDic setValue:self.orderCode forKey:@"mainOrderCode"];
                if(![DCSpeedy isBlankString:self.massageCode] == YES){
                    [muDic setValue:self.massageCode forKey:@"messageCode"];
                    [muDic setValue:CJStringWithFormat(@"%@",lastWeight) forKey:@"residueNumber"];
                }
                urlString = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_DETAIL_RECEIVE);
                
            } else if (state == 1) {
                
                [muDic setValue:self.orderCode forKey:@"mainOrderCode"];
                if(![DCSpeedy isBlankString:self.massageCode] == YES){
                    [muDic setValue:self.massageCode forKey:@"messageCode"];
                    [muDic setValue:CJStringWithFormat(@"%@",notReceivedCount) forKey:@"residueCarNumber"];
                }
                urlString = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_DETAIL_RECEIVE);
                
            } else if (state == 2) {
                
                if ([DCSpeedy isBlankString:_shuLiangString] == YES || [DCSpeedy isBlankString:_danJiaString] == YES || [DCSpeedy isBlankString:_timeString] == YES) {
                    [XSInfoView showInfo:@"信息不能为空" onView:self.view];
                    return;
                }
                
                [muDic setValue:_shuLiangString forKey:@"bidWeight"];
                [muDic setValue:_danJiaString forKey:@"bidPrice"];
                [muDic setValue:_timeString forKey:@"arrivalTime"];
                [muDic setValue:self.orderCode forKey:@"mainOrderCode"];
                
                urlString = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_BID_BID);
                
            } else if (state == 3) {
                
                if ([DCSpeedy isBlankString:_danJiaString] == YES || [DCSpeedy isBlankString:_timeString] == YES) {
                    [XSInfoView showInfo:@"信息不能为空" onView:self.view];
                    return;
                }
                
                [muDic setValue:_danJiaString forKey:@"bidPrice"];
                [muDic setValue:_timeString forKey:@"arrivalTime"];
                [muDic setValue:self.orderCode forKey:@"mainOrderCode"];
                
                urlString = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_BID_BID);
                
            } else if (state == 4) {
                
                if ([DCSpeedy isBlankString:_shuLiangString] == YES || [DCSpeedy isBlankString:_cheShuString] == YES) {
                    [XSInfoView showInfo:@"信息不能为空" onView:self.view];
                    return;
                }
                
                [muDic setValue:_shuLiangString forKey:@"perWeight"];
                [muDic setValue:_cheShuString forKey:@"coalNumber"];
                [muDic setValue:self.orderCode forKey:@"mainOrderCode"];
                if(![DCSpeedy isBlankString:self.massageCode] == YES){
                    [muDic setValue:self.massageCode forKey:@"messageCode"];
                    [muDic setValue:CJStringWithFormat(@"%@",lastWeight) forKey:@"residueNumber"];
                }
                urlString = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_DETAIL_NEWMULTIRECEIVE);
                
            } else if (state == 5) {
                
                if ([DCSpeedy isBlankString:_cheShuString] == YES) {
                    [XSInfoView showInfo:@"车数不能为空" onView:self.view];
                    return;
                }
                
                [muDic setValue:_cheShuString forKey:@"coalNumber"];
                [muDic setValue:self.orderCode forKey:@"mainOrderCode"];
                if(![DCSpeedy isBlankString:self.massageCode] == YES){
                    [muDic setValue:self.massageCode forKey:@"messageCode"];
                    [muDic setValue:CJStringWithFormat(@"%@",notReceivedCount) forKey:@"residueCarNumber"];
                }
                
                urlString = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_DETAIL_NEWMULTIRECEIVE);
                
            } else if (state == 6) {
                
                if ([DCSpeedy isBlankString:_shuLiangString] == YES || [DCSpeedy isBlankString:_danJiaString] == YES || [DCSpeedy isBlankString:_cheShuString] == YES ||[DCSpeedy isBlankString:_timeString] == YES) {
                    [XSInfoView showInfo:@"信息为空" onView:self.view];
                    return;
                }
                
                //            [muDic setValue:_shuLiangString forKey:@"perWeight"];
                [muDic setValue:_shuLiangString forKey:@"bidWeight"];
                [muDic setValue:_danJiaString forKey:@"bidPrice"];
                [muDic setValue:_cheShuString forKey:@"bidCount"];
                [muDic setValue:_timeString forKey:@"arrivalTime"];
                [muDic setValue:self.orderCode forKey:@"mainOrderCode"];
                
                urlString = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_BID_NEWMULTIBID);
                
            } else if (state == 7) {
                
                if ([DCSpeedy isBlankString:_danJiaString] == YES || [DCSpeedy isBlankString:_cheShuString] == YES ||[DCSpeedy isBlankString:_timeString] == YES) {
                    [XSInfoView showInfo:@"信息为空" onView:self.view];
                    return;
                }
                
                [muDic setValue:_danJiaString forKey:@"bidPrice"];
                [muDic setValue:_cheShuString forKey:@"bidCount"];
                [muDic setValue:_timeString forKey:@"arrivalTime"];
                [muDic setValue:self.orderCode forKey:@"mainOrderCode"];
                
                urlString = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_BID_NEWMULTIBID);
                
            }
            
            //6-20 新增经纬度参数
            [muDic setValue:[UserDefaultUtil valueForKey:LONGITUDE] forKey:@"longitude"];
            [muDic setValue:[UserDefaultUtil valueForKey:LATITUDE] forKey:@"latitude"];
            [muDic setValue:[UserDefaultUtil valueForKey:USER_TOKEN] forKey:@"token"];
           
            _isRequesting = YES;

            [HTTPManager postNetworkRequest:urlString withParameter:muDic withVC:self netName:@"接单" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:msg onView:self.view];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    
                    _isRequesting = NO;
//                    if([self.type isEqualToString:@"1"]){
//                    
                        [self.navigationController popToRootViewControllerAnimated:YES];
//                    }else{
//                        [self.navigationController popViewControllerAnimated:YES];
//                    }
                    [KNotificationCenter postNotificationName:@"popToHomePushJieDan" object:nil];

                });
                
            } failure:^(NSInteger code, NSString *msg) {
                
                _isRequesting = NO;
                if([msg isEqualToString:@"您有未完成的订单，请完成订单后在抢单！"]){
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示!" message:msg preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction* actionsentient = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                       
                    }];
                    UIAlertAction* action = [UIAlertAction actionWithTitle:@"继续完成订单" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        [KNotificationCenter postNotificationName:@"popToHomePushDaiYunShu" object:nil];
                    }];
                    [alert addAction:actionsentient];
                    [alert addAction:action];
                    [self presentViewController:alert animated:YES completion:nil];
                }else if ([msg isEqualToString:@"接单失败，该货源单要求司机必须加入车队，未加入车队不能接单"]){
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示!" message:msg preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction* actionsentient = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                       
                    }];
                    UIAlertAction* action = [UIAlertAction actionWithTitle:@"加入车队" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        //加入车队
                        CarTeamViewController *ctvc = [[CarTeamViewController alloc] init];
                        [self.navigationController pushViewController:ctvc animated:YES];
                    }];
                    [alert addAction:actionsentient];
                    [alert addAction:action];
                    [self presentViewController:alert animated:YES completion:nil];
                }else if([msg containsString:@"账号已被冻结，禁止接单"]){
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示!" message:msg preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction* actionsentient = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                       
                    }];
                    [alert addAction:actionsentient];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
            
        } else if (index == 1100) {
            
            CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
            webVC.titleString = @"运输交易协议";
            webVC.urlString = CJStringWithFormat(@"%@/agreement/agreement.html?agreementType=5", BasicDomainURL);
//            webVC.urlString = CJStringWithFormat(@"%@/agreement/driverOrderReceivingAgreement.html", BasicDomainURL);
            
            webVC.state = 1;
            [self.navigationController pushViewController:webVC animated:YES];
        }
        
    }
    
    
}

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置定位超时时间
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    
    //设置允许连续定位逆地理
    [self.locationManager setLocatingWithReGeocode:YES];
    
    [self.locationManager startUpdatingLocation];
}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    
}

#pragma mark - AMapLocationManager Delegate

/**
 *  @brief 连续定位回调函数.注意：如果实现了本方法，则定位信息不会通过amapLocationManager:didUpdateLocation:方法回调。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param location 定位结果。
 *  @param reGeocode 逆地理信息。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    DebugLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.longitude) forKey:LONGITUDE];
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.latitude) forKey:LATITUDE];
    
    //详细信息
    if (reGeocode)
    {
        DebugLog(@"reGeocode:%@", reGeocode);
    }
    
}

- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestAlwaysAuthorization];
}

/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    
    DebugLog(@"定位error：%@",error);
}
- (void)dealloc
{
    [self cleanUpAction];
}

#pragma mark - lazyLoad
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NavHeight)];
//        _scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (OderDetailTFView *)oderDetailTFView {
    if (!_oderDetailTFView) {
        _oderDetailTFView = [[OderDetailTFView alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 220)];
        _oderDetailTFView.delegate = self;
        _oderDetailTFView.backgroundColor = [UIColor whiteColor];
    }
    return _oderDetailTFView;
}
- (OrderInfoView *)orderInfoView {
    if (!_orderInfoView) {
        _orderInfoView = [[OrderInfoView alloc] initWithFrame:CGRectMake(0, _oderDetailTFView.cy_bottom + 10, ScreenW, 350 + 16*35)];
        _orderInfoView.backgroundColor = BackgroundColor;
        if ([[UserDefaultUtil valueForKey:Login_Branch][@"isTax"] integerValue] == 1) {
            //天津税务开关打开
            _orderInfoView.height = 350 + 16*35;
        }
        NSInteger driverType = [[UserDefaultUtil valueForKey:DRIVER_TYPE] integerValue];
        if ([_dataDic[@"qrCodeOnOff"] integerValue] == 1 && (driverType == 0 || driverType == 2) ) {
            //二维码装卸货功能打开
            _orderInfoView.height = 390 + 16*35 + 200;
        }
    }
    return _orderInfoView;
}
@end
